﻿using System;
using System.Linq;
using Breeze.WebApi;
using LunchLearn.WebApi.Hubs;
using LunchLearn.WebApi.Domain;
using Microsoft.AspNet.SignalR;
using LunchLearn.WebApi.Infrastructure;
using System.Collections.Generic;
using LunchLearn.WebApi.Infrastructure.TrackingServices;

namespace LunchLearn.WebApi.Repository
{
    public class ContextProvider : EFContextProvider<LunchLearnContext>, IContextProvider, IDisposable
    {
        private IChangeTrackingService _changeTrackingService;

        public ContextProvider(IChangeTrackingService changeTrackingService)
        {
            _changeTrackingService = changeTrackingService;
            this.Context.Configuration.LazyLoadingEnabled = false;
        }

        protected override List<KeyMapping> SaveChangesCore(Dictionary<Type, List<EntityInfo>> saveMap)
        {
            var saveChanges = base.SaveChangesCore(saveMap);
            foreach (var sm in saveMap.Select(x=> x.Value))
            {
                foreach (var change  in sm)
                {
                    _changeTrackingService.Track(change, this.Context);
                }
            }
            return saveChanges;
        }

        public void Dispose()
        {
            Context.Dispose();
        }
    }
}